
/**
 * 首页登陆 
 */
const postModel = require("../models/post");
const commentModel = require("../models/comment");
const config = require("config-lite")(__dirname);
const uuid = require("uuid");
const moment = require('moment');
const userModel = require("../models/user");
const fs = require("fs")

/**
 * 显示登陆页
 * @param {*} ctx 
 * @param {*} next 
 */
exports.showIndex = async (ctx, next) => {
    var data = null,type = 0,total = 0;
    var page = ctx.query.page ? (ctx.query.page - 1) : 0;
    var pageSize = config.pageSize;
    if(ctx.query.type){
        //实现分页 
        data = await postModel.findList({type : ctx.query.type, isUsing : 1},page,pageSize);
        total = await postModel.findLength({type : ctx.query.type, isUsing : 1});//查询总条数
    }else {
        data = await postModel.findList({isUsing : 1},page,pageSize);
        total = await postModel.findLength({isUsing : 1});//查询总条数
    }
    var hotList = await postModel.findHotList({isUsing : 1});//查询热门列表
    await ctx.render('index', {
        title     : '菜菜的博客',
        data      : data,
        total     : total,
        page      : page,
        pageSize  : pageSize,
        totalPage : Math.ceil(total / pageSize),
        hotList   : hotList,
        isLogin   : ctx.cookies.get("uuid") ? true : false
    })
}
/**
 * 显示详情页
 * @param {*} ctx 
 * @param {*} next 
 */
exports.showDetail =  async (ctx, next) => {
    //查询详情数据
    var data = await postModel.findDetail({postId : ctx.params.id.trim()}),num = 2,like = false;
    if(data[0].readNum){
        num = data[0].readNum + 1;
    }
    if(data[0].like.indexOf(ctx.cookies.get("uuid")) >= 0){
        //点赞过
        like = true;
    }
    /**
     * 更新阅读量
     */
    var updateReadNum = await postModel.updateData({postId : ctx.params.id.trim()},{$set: {readNum : num}})
    var last = await postModel.findLast({createTime : data[0].createTime,uuid : data[0].uuid});//查询上一条
    var next = await postModel.findNext({createTime : data[0].createTime,uuid : data[0].uuid});//查询下一条
    var commentList = await commentModel.getPostComment({postId : ctx.params.id.trim()});//获取当前文章的所有评论
    var temData = {
        title      : data[0].title,
        content    : data[0].content,
        uuid       : data[0].uuid,
        userName   : data[0].userName,
        descript   : data[0].descript,
        label      : data[0].label,
        createTime : data[0].createTime,
        postId     : data[0].postId,
        typeName   : data[0].typeName,
    }
    var hotList = await postModel.findHotList({isUsing : 1});
    await ctx.render('detail', {
        title   : '博客详情',
        data    : temData,
        hotList ,
        last    : last,
        next    : next,
        postId  : ctx.params.id,
        commentList,
        isLogin : ctx.cookies.get("uuid") ? true : false,
        like    : like
    })
}
/**
 * 显示个人信息页面
 * @param {*} ctx 
 * @param {*} next 
 */
exports.showInfo = async (ctx , next) => {
    var data = await userModel.findUser({uuid : ctx.cookies.get("uuid")});
    await ctx.render('myInfo', {
        title : "个人详情",
        data  : data[0],
        isLogin   : ctx.cookies.get("uuid") ? true : false
    })
}
/**
 * 上传图片
 * @param {*} ctx 
 * @param {*} next 
 */
exports.upload = async (ctx,next) =>{
    ctx.body = {  
        errno: 0,
        data: ctx.req.files.map((item)=>{
            return item.path.substr(6,item.path.length);//去掉public/
        })
    }  
}
/**
 * 图片是base64编码
 * @param {*} ctx 
 * @param {*} next 
 */
exports.uploadHead = async (ctx,next)=>{
    var img = ctx.request.body.img,imgUrl = "/uploads/heads/" + new Date().getTime() + ".png";
    var base64Data = img.replace(/^data:image\/\w+;base64,/, "");
    var dataBuffer = new Buffer(base64Data, 'base64');
    try {
        fs.writeFileSync("public"+ imgUrl, dataBuffer);
        ctx.body = {
            code     : "0",
            message  : "success",
            fileUrl  : imgUrl
        }
    }catch(e){
        ctx.body = {
            code    : "-1",
            message : "error"
        }
    } 
}
/**
 * 评论
 * @param {*} ctx 
 * @param {*} next 
 */
exports.comment = async (ctx ,next ) => {
    const params = ctx.request.body;//获取参数
    params.commentUuid = uuid.v1();
    params.createTime =  moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    var cm = await commentModel.saveComment(params);
    if(cm){
        ctx.body = {
            code    : "0",
            message : "success"
        }
    }else {
        ctx.body = {
            code    : "-1",
            message : "error"
        }
    }
}
/**
 * 获取评论列表
 * @param {*} ctx 
 * @param {*} next 
 */
exports.getComentList = async (ctx, next) => {
    var commentList = await commentModel.getPostComment(ctx.query)
    if(commentList){
        ctx.body = {
            code    : "0",
            message : "success",
            commentList 
        }
    }else {
        ctx.body = {
            code    : "-1",
            message : "error"
        }
    }
}
/**
 * 保存用户信息
 * @param {*} ctx 
 * @param {*} next 
 */
exports.saveUserInfo = async (ctx, next) => {
    var params = ctx.request.body;
    var saveFlag = await userModel.updateUserInfo(params);
    if(saveFlag){
        ctx.body = {
            code    : "0",
            message : "success"
        }
    }else {
        ctx.body = {
            code    : "-1",
            message : "error"
        }
    }
}
